package edu.gyc.producer.consumer;

import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class N95{
    private int id;
    private String type;

    public N95(int id, String type) {
        this.id = id;
        this.type = type;
    }

    @Override
    public String toString() {
        return "N95{" +
                "id=" + id +
                ", type='" + type + '\'' +
                '}';
    }
}

class N95Factory{
    
    private static final int STOCKNUMS=20;
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    private BlockingQueue<N95> n95BlockingQueue = new ArrayBlockingQueue<>(STOCKNUMS - 10);

    public void put() {
        for (int i = 0; i < STOCKNUMS; i++) {
             int pid=atomicInteger.incrementAndGet();
            N95 n95 = new N95(pid, "医用");
            try {
                Thread.sleep(100);
                // boolean r = n95BlockingQueue.offer(n95);
                //比较有等待的offer输出结果
                boolean r = n95BlockingQueue.offer(n95, 100, TimeUnit.MILLISECONDS);
                if (r) {
                    System.out.println(Thread.currentThread().getName()+"\t生产的"+n95+"入库成功");
                }else {
                    System.out.println(Thread.currentThread().getName()+"\t生产的"+n95+"入库失败");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }



        }
        
    }
    public void get() {
        for (int i = 0; i < STOCKNUMS; i++) {
          
            try {
                Thread.sleep(50);
                // N95 n95 = n95BlockingQueue.poll();
                N95 n95 = n95BlockingQueue.poll(50, TimeUnit.MILLISECONDS);
                if (n95!=null) {
                    System.out.println(Thread.currentThread().getName()+"\t提货"+n95+"成功");
                }else {
                    System.out.println(Thread.currentThread().getName()+"\t提货"+n95+"失败");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }

    }
}
public class N95BlockQueue {
    public static void main(String[] args) {
      
        N95Factory n95Factory=new N95Factory();
        new Thread(()->{


                n95Factory.put();

        },"生产者1").start();
        new Thread(()->{

                n95Factory.put();

        },"生产者2").start();
        new Thread(()->{


                n95Factory.get();

        },"消费者1").start();

        new Thread(()->{


                n95Factory.get();

        },"消费者2").start();


    }
}
